package org.jeecg.modules.flower.controller;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.mapper.FlowerTagpreMapper;
import org.jeecg.modules.flower.service.*;
import org.jeecg.modules.flowerutil.PeriodUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 删除错误的入库数据，且已经出库过的！！！！！！！！！gf2022年8月8日14:43:48
 */
@Api(tags = "错误数据纠正！！！！！！！！")
@RestController
@RequestMapping("/flower/wrong")
@Slf4j
public class DeleteWrongIn {
    @Autowired
    private ITFlowerTagIn2Service flowerTagInService;

    @Autowired
    private IFlowerOutorderPreService flowerOutorderPreService;

    @Autowired
    private IFlowerOutorderPreinfoService flowerOutorderPreinfoService;

    @Autowired
    private IFlowerTagpreService flowerTagpreService;

    @Autowired
    private FlowerTagpreMapper flowerTagpreMapper;

    @Autowired
    private IFlowerPreinfoService flowerPreinfoService;


    @Autowired
    private IFlowerTagInfoService flowerTagInfoService;


    @ApiOperation(value = "测试", notes = "测试")
    @GetMapping(value = "/test")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> test() throws ParseException {

        PeriodUtils p = new PeriodUtils();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("getNowPeriod", p.getNowPeriod());
        jsonObject.put("getPrePeriod", p.getPrePeriod());
        jsonObject.put("getShowDay", String.valueOf(p.getShowDay()));

        return Result.ok(jsonObject);

    }

    @ApiOperation(value = "删除错误的入库数据，且已经预出库过的", notes = "删除错误的入库数据，且已经预出库过的")
    @GetMapping(value = "/do")
    @Transactional(rollbackFor = Exception.class)
    public Integer tttt(@RequestParam(name = "xuhao") String xuhao) {
        if (StringUtils.isBlank(xuhao)) {
            throw new RuntimeException("序号为空！！！" + xuhao);
        }
        int rest = 0;
        LambdaQueryWrapper<TFlowerTagIn2> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(TFlowerTagIn2::getNo, xuhao);
        TFlowerTagIn2 flowerTagIn = flowerTagInService.getOne(lambdaQueryWrapper);
        String inid = flowerTagIn.getId();

        LambdaQueryWrapper<FlowerTagInfo> infoLambdaQueryWrapper = new LambdaQueryWrapper();
        infoLambdaQueryWrapper.eq(FlowerTagInfo::getInId, inid);
//     1、     查出台账id，
        List<FlowerTagInfo> tagInfoListlist = flowerTagInfoService.list(infoLambdaQueryWrapper);

        List ids = new ArrayList();
        for (FlowerTagInfo flowerTagInfo : tagInfoListlist) {
            ids.add(flowerTagInfo.getId());
        }

//      2、根据tagpre的inid，  查出预出库台账数据，
//      3、再去台账中查找相同型号的数据id，替换到预出库台账的inid中，更新台账数据状态。同时删除原台账数据。

        for (FlowerTagInfo flowerTagInfo : tagInfoListlist) {
            if ("2".equals(flowerTagInfo.getState())) {

                LambdaQueryWrapper<FlowerTagpre> tagpreQueryWrapper = new LambdaQueryWrapper();
                tagpreQueryWrapper.eq(FlowerTagpre::getInId, flowerTagInfo.getId());
                List<FlowerTagpre> flowerTagpreList = flowerTagpreService.list(tagpreQueryWrapper);//查出预出库台账数据，
                if (flowerTagpreList.size() != 1) {
                    throw new RuntimeException("flowerTagpreList！不等于1！！");
                }
                FlowerTagpre flwertagpreone = flowerTagpreList.get(0);
                log.info("旧的taginfo--id" + flowerTagInfo.getId());
                log.info("pre--tag的--id" + flwertagpreone.getId());
                log.info("pre--tag的--inid" + flwertagpreone.getInId());


                //根据品类variety、varietyCode、规格packingSpecifications、花杆长度flowerPoleLength、等级classes、数量number
                //自动去台账进行出库
                String varietyCode = flowerTagInfo.getVarietyCode();
                String packingSpecifications = flowerTagInfo.getPackingSpecifications();
                String flowerPoleLength = flowerTagInfo.getFlowerPoleLength();
                String storehouse = flowerTagInfo.getStorehouse();
                String number = "1";

                Date stockOutTime = flowerTagInfo.getStockInTime();

                LambdaQueryWrapper<FlowerTagInfo> taginfoQuery = new LambdaQueryWrapper<>();

                taginfoQuery.eq(FlowerTagInfo::getVarietyCode, varietyCode);
                taginfoQuery.eq(FlowerTagInfo::getStorehouse, storehouse);
                taginfoQuery.eq(FlowerTagInfo::getPackingSpecifications, packingSpecifications);
                taginfoQuery.eq(FlowerTagInfo::getFlowerPoleLength, flowerPoleLength);
                taginfoQuery.eq(FlowerTagInfo::getState, 1);//已入库的台账

                taginfoQuery.notIn(FlowerTagInfo::getId, ids);
                taginfoQuery.orderByAsc(FlowerTagInfo::getSortTime);

                Page<FlowerTagInfo> page = new Page<FlowerTagInfo>(1, 1);
                IPage<FlowerTagInfo> tageinfoPage = flowerTagInfoService.page(page, taginfoQuery);
                List<FlowerTagInfo> records = tageinfoPage.getRecords();
                if (records.size() != 1) {
                    throw new RuntimeException("查找新的台账数据有误！！！" + varietyCode);
                }
                String newtaginfoid = records.get(0).getId();
                log.info("新的taginfo--id" + newtaginfoid);

                flwertagpreone.setInId(newtaginfoid);//更新预出库台账的taginid
                flowerTagpreService.updateById(flwertagpreone);

                //更新新taginfo的状态
                FlowerTagInfo flowerTagInfoNew = new FlowerTagInfo();
                flowerTagInfoNew.setId(newtaginfoid);
                flowerTagInfoNew.setState("2");
                flowerTagInfoNew.setStockOutTime(stockOutTime);
                flowerTagInfoNew.setStockOutUser(flowerTagInfo.getStockOutUser());
                flowerTagInfoService.updateById(flowerTagInfoNew);
                flowerTagInfo.setState("1");
                flowerTagInfoService.updateById(flowerTagInfo);//删除旧的台账的数据状态
                rest++;
            }
        }

        flowerTagIn.setState("1");
        flowerTagInService.updateById(flowerTagIn);


        log.info("============" + rest);
        log.info("============" + rest);
        log.info("============" + rest);
        log.info("============" + rest);
        log.info("============" + rest);
        log.info("============" + rest);
        log.info("============" + rest);
        log.info("============" + rest);
        log.info("============" + rest);
        log.info("============" + rest);
        return rest;
    }

    @ApiOperation(value = "报表test，报表test", notes = "报表test，报表test")
    @GetMapping(value = "/getDataReport")
    public JSONObject ttqwertt(@RequestParam(name = "id") String id) {
        log.info(id);
        log.info(id);
        log.info(id);
        log.info(id + "=========================");
        log.info(id);
        log.info(id);
        Page<FlowerTagInfo> page = new Page<FlowerTagInfo>(1, 10);
        LambdaQueryWrapper<FlowerTagInfo> queryWrapper = new LambdaQueryWrapper<>();
        IPage<FlowerTagInfo> page1 = flowerTagInfoService.page(page, queryWrapper);


        List<FlowerTagInfo> records = page1.getRecords();

        JSONObject dd = new JSONObject();
        dd.put("data", records);

        return dd;
    }


    @ApiOperation(value = "错误数据处理！！！预出库管理删除，预出库台账未删除处理方法！！查找新数据更新销售确认的id即可", notes = "错误数据处理！！！预出库管理删除，预出库台账未删除处理方法！！查找新数据更新销售确认的id即可")
    @GetMapping(value = "/doOutOrderPreData")
    public Integer doOutOrderPreData() {
        Integer rest = 0;
        //查找是否存在该情况

        QueryWrapper<FlowerTagpre> queryWrapper123 = new QueryWrapper<>();
//        queryWrapper123.not( "outorder_id"," select aa.id from   t_flower_outorder_preinfo  aa");
        queryWrapper123.notInSql("outorder_id"," SELECT id FROM t_flower_outorder_preinfo aa   ");
//        queryWrapper123.notExists(" SELECT 1 FROM t_flower_outorder_preinfo aa  where aa.id =outorder_id");
        List<FlowerTagpre> list = flowerTagpreService.list(queryWrapper123);
        for (FlowerTagpre flowerTagpre : list) {
            log.info("修改id: " + flowerTagpre.getId() + "    " + rest);
            Integer state = flowerTagpre.getState();
            String preSureId = flowerTagpre.getPreSureId();
            String stockOutUser = flowerTagpre.getStockOutUser();
            Date stockOutTime = flowerTagpre.getStockOutTime();
            String accountno = flowerTagpre.getAccountno();
            String channel = flowerTagpre.getChannel();
            String storehouse = flowerTagpre.getStorehouse();
            String varietyCode = flowerTagpre.getVarietyCode();
            String packingSpecifications = flowerTagpre.getPackingSpecifications();
            String flowerPoleLength = flowerTagpre.getFlowerPoleLength();
            if (state == 2) {
                LambdaQueryWrapper<FlowerTagpre> tagpreQuery = new LambdaQueryWrapper<>();
                tagpreQuery.eq(FlowerTagpre::getChannel, channel);
                tagpreQuery.eq(FlowerTagpre::getAccountno, accountno);
                tagpreQuery.eq(FlowerTagpre::getStorehouse, storehouse);
                tagpreQuery.eq(FlowerTagpre::getVarietyCode, varietyCode);
                tagpreQuery.eq(FlowerTagpre::getPackingSpecifications, packingSpecifications);
                tagpreQuery.eq(FlowerTagpre::getFlowerPoleLength, flowerPoleLength);
                tagpreQuery.eq(FlowerTagpre::getState, 1);//已入库的台账
                tagpreQuery.orderByAsc(FlowerTagpre::getStockInTime);
                List<FlowerTagpre> flowerTagpreList = flowerTagpreService.list(tagpreQuery);
                if (flowerTagpreList.size() == 0) {
                    log.info( "扣减库存不够！" + varietyCode );
                    log.info( "扣减库存不够！" + varietyCode );
                    log.info( "扣减库存不够！" + varietyCode );
                    continue;
//                    throw new RuntimeException("扣减库存不够！" + varietyCode);
                }
                FlowerTagpre flowerTagpre1 = flowerTagpreList.get(0);
                FlowerTagpre flowerTagpre11 = new FlowerTagpre();
                flowerTagpre11.setId(flowerTagpre1.getId());
                flowerTagpre11.setPreSureId(preSureId);
                flowerTagpre11.setState(2);
                flowerTagpre11.setStockOutTime(stockOutTime);
                flowerTagpre11.setStockOutUser(stockOutUser);
                flowerTagpreService.updateById(flowerTagpre11);//新的台账数据

                //旧的的台账数据
                flowerTagpreService.removeById(flowerTagpre.getId() ) ;

//                FlowerTagpre flowerTagpre2 = new FlowerTagpre();
//                flowerTagpre2.setId(flowerTagpre.getId());
//                flowerTagpre2.setPreSureId("0000000000000000000");
//                flowerTagpre2.setState(1);
//                flowerTagpreService.updateById(flowerTagpre2) ;
//                不生效，可能是两个updateById，第二个不生效

                rest++;
            }
        }

//        if(1==1){
//            throw new RuntimeException("------------------！" );
//        }

        return rest;
    }


    public int tt(String processBusinessKey){
        log.info(" 进入到    DeleteWrongIn    :" + processBusinessKey);

        return  999;
    }

}
